package com.weds.data_sync.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weds.data_sync.constant.ScriptServiceConstant;
import com.weds.data_sync.pojo.dto.LoginDto;
import com.weds.data_sync.pojo.entity.DataSyncAccountDO;
import com.weds.data_sync.mapper.DataSyncAccountMapper;
import com.weds.data_sync.service.AccountService;
import com.weds.data_sync.util.CommonUtil;
import com.weds.data_sync.util.JsonData;
import com.weds.data_sync.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.weds.data_sync.constant.BizCodeEnum.*;

/**
 * <p>
 * 数据同步账户表 服务实现类
 * </p>
 *
 * @author lhw
 * @since 2023-12-29
 */
@Service
public class AccountServiceImp extends ServiceImpl<DataSyncAccountMapper, DataSyncAccountDO> implements AccountService {

    @Autowired
    private DataSyncAccountMapper dataSyncAccountMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public JsonData login(LoginDto loginDto, HttpServletRequest request) {
        Boolean checkFlag = CommonUtil.checkImageCaptcha(request, redisTemplate, loginDto.getVerifyCode());
        if (!checkFlag) {
            return JsonData.buildResult(VERIFY_CODE_ERROR);
        }
        DataSyncAccountDO accountDO = dataSyncAccountMapper.selectOne(new QueryWrapper<DataSyncAccountDO>()
                .eq("username", loginDto.getUsername())
                .last("limit 1"));
        if (Objects.isNull(accountDO)) {
            return JsonData.buildResult(USER_PWD_ERROR);
        }
        String encryptPwd = SecureUtil.md5(loginDto.getPassword() + ScriptServiceConstant.COMMON_SECRET);
        if (encryptPwd.equalsIgnoreCase(accountDO.getPassword())) {
            Map<String, Object> jwtData = new HashMap<>();
            jwtData.put("userId", accountDO.getId());
            jwtData.put("username", accountDO.getUsername());
            String token = JwtUtil.createToken(accountDO.getUsername(), jwtData);
            return JsonData.buildSuccess(token);
        }
        return JsonData.buildResult(COMMON_FAIL);
    }
}
